<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card>
      <div class="input_btn">
        <el-input
          placeholder="请输入内容"
          clearable
          v-model="queryInfo.query"
          class="input-with-select"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="getUsersList"
          ></el-button>
        </el-input>
        <el-button
          id="addUsers"
          label="label"
          type="primary"
          @click="addDialogVisible = true"
          >添加用户</el-button
        >
      </div>
      <el-table :data="usersList" border stripe style="width: 100%">
        <el-table-column type="index" label="#" width="50"></el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="180"
        ></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column
          prop="role_name"
          label="角色"
          width="180"
        ></el-table-column>
        <el-table-column label="状态" width="80">
          <template slot-scope="scope">
            <!--slot 作用域插槽-->
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240">
          <template slot-scope="scope">
            <el-button
              label="label"
              type="primary"
              size="mini"
              @click="showEditDialog(scope.row.id)"
              >修改</el-button
            >
            <el-tooltip
              class="item"
              effect="light"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button label="label" type="warning" size="mini"
                >分配角色</el-button
              ></el-tooltip
            >
            <el-tooltip
              class="item"
              effect="light"
              content="删除"
              placement="top"
              :enterable="false"
            >
              <el-button
                label="label"
                type="danger"
                size="mini"
                @click="delUser(scope.row.id)"
                >删除</el-button
              ></el-tooltip
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[10, 15, 20, 30]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="40%"
      @close="addDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        label-position="right"
        label-width="80px"
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域，有slot插槽 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="40%"
      @close="editClosed"
    >
      <!-- 主体部分 -->
      <el-form
        label-position="right"
        label-width="80px"
        :rules="editFormRules"
        ref="editFormRef"
        :model="editForm"
      >
        <el-form-item label="用户名">
          <el-input disabled v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!--分配角色对话框 -->
    <!-- <el-dialog
      title="分配角色"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <span>这是一段信息</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog> -->
    <!-- 删除角色对话框 -->
    <el-dialog title="删除角色" :visible.sync="delDialogVisible" width="30%">
      <span>确定要删除角色吗！？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getUsersList();
  },
  data() {
    //验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      //邮箱正则
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;

      if (regEmail.test(value)) {
        return cb();
      }

      cb(new Error("请输入合法的邮箱"));
    };
    //验证电话的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;

      if (regMobile.test(value)) {
        return cb();
      }

      cb(new Error("请输入合法的电话"));
    };
    return {
      usersList: [],
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 10,
      },
      total: 0,
      ismg_state: true,
      //打开添加用户对话框
      addDialogVisible: false,
      //打开修用户对话框
      editDialogVisible: false,
      //删除角色对话框
      delDialogVisible: false,
      //添加用户的表单数据
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      //添加用户表单的验证规则
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 16, message: "长度在3-16之间", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 16, message: "长度在3-16之间", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入电话", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },

      //修改用户的数据列表
      editForm: {
        username: "",
        email: "",
        mobile: "",
      },
      //修改用户的验证规则
      editFormRules: {
        email: [
          { required: false, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: false, message: "请输入电话", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      //删除用户的列表
      delForm: {},
    };
  },
  methods: {
    async getUsersList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取用户列表失败");
      this.usersList = res.data.users;
      this.total = res.data.total;
    },
    //监听页面条数变化
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize;
      this.getUsersList(); //重新获取用户列表
    },
    //监听页码值改变
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage;
      this.getUsersList();
    },
    //改变状态swith
    async userStateChanged(userinfo) {
      console.log(userinfo);
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );

      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;
        return this.$message.error("获取状态失败");
      }
      this.$message.success("更新用户状态成功！");
    },
    //监听添加用户关闭
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    //点击按钮添加新用户
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;

        //发起真正的请求
        const { data: res } = await this.$http.post("users", this.addForm);

        if (res.meta.status !== 201)
          return this.$message.error("添加用户失败！");

        this.$message.success("添加用户成功!");
        this.addDialogVisible = false;
        this.getUsersList();
      });
    },

    //修改用户,点击按钮打开对话框获取用户信息
    async showEditDialog(id) {
      // console.log(id);
      const { data: res } = await this.$http.get("users/" + id);

      if (res.meta.status !== 200) {
        return this.$message.error("获取用户信息失败");
      }
      this.editForm = res.data;
      this.editDialogVisible = true;
    },

    //监听修改对话框的打开，重置表单
    editClosed() {
      this.$refs.editFormRef.resetFields();
    },
    //提交修改
    editUserInfo() {
      //提交之前进行预验证
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;

        //发起请求
        const { data: res } = await this.$http.put(
          "users/" + this.editForm.id,
          { email: this.editForm.email, mobile: this.editForm.mobile }
        );

        if (res.meta.status !== 200) return this.$message.error("修改用户失败");

        this.editDialogVisible = false;
        this.getUsersList();
        this.$message.success("修改用户成功");
      });
    },
    //打开删除角色对话框
    async delUser(id) {
      const { data: res } = await this.$http.get("users/" + id);
      this.delForm = res.data;
      this.delDialogVisible = true;
    },

    //点击确定删除角色
    deleteUser() {
      this.$http.delete("users/" + this.delForm.id);
      this.delDialogVisible = false;
      this.getUsersList();
      this.$message.success("删除用户成功！");
    },
  },
};
</script>

<style scoped>
.el-card {
  margin-top: 20px;
}
.el-table {
  margin-top: 20px;
}

.el-input {
  width: 300px;
}

.input_btn {
  display: flex;
}

.input_btn #addUsers {
  margin-left: 15px;
}

.el-pagination {
  margin-top: 30px;
}
</style>
